package wzq.cn.wuziqi.model;

import android.content.Context;
import android.content.Intent;

import java.util.ArrayList;

import wzq.cn.wuziqi.RC;
import wzq.cn.wuziqi.algorithm.CoreAlgorithm;
import wzq.cn.wuziqi.algorithm.ScoreTable;
import wzq.cn.wuziqi.core.AI;
import wzq.cn.wuziqi.core.MoveTaskQuenue;
import wzq.cn.wuziqi.core.OnActionListener;
import wzq.cn.wuziqi.core.OnMoveFinishedListener;
import wzq.cn.wuziqi.core.VerifySuccess;
import wzq.cn.wuziqi.utils.LogUtils;

/**
 * 人永远在黑色方，对面就是白色方
 */
public class ChessBoard implements OnMoveFinishedListener {

    /**
     * x,y轴的数量，就是棋盘的横向与纵向的数量
     */
    public  int chessBoardxNumber = 15;
    public  int chessBoardyNumber = 15;


    public int successNumber = 5;

    public Side[] twoSide = new Side[2];

    //所有获胜的结果，用来推演下一步
    public  SuccessResult[] results;

    public ScoreTable firstSideTable,secondSideTable;

    public ArrayList<OnActionListener> listeners = new ArrayList<>();

    //桌面结果
    public PointU[][] mDeskResult;

    public Side mCurrentSide = new Side();

    public int timeCountEachStep = 10;
    //是否是人机 AI 人机
    private TYPE mType = TYPE.AI;
    private AI mAiMachine;

    public Context ctx;

    public SuccessResult successResult = null;//成功的5个棋子


    boolean isDebugAi = true;

    public TYPE getmType() {
        return mType;
    }

    public void setmType(TYPE mType) {
        this.mType = mType;
    }

    /**
     * @param xNumber
     * @param yNumber
     */
    public ChessBoard(Context ctx,int xNumber, int yNumber) {
        chessBoardxNumber = xNumber;
        chessBoardyNumber = yNumber;
        this.ctx = ctx;
        mAiMachine = new AI();
        initChessBoard();
    }

    //初始化
    private void initChessBoard() {
        results = CoreAlgorithm.getAllSuccessResults(chessBoardxNumber, chessBoardyNumber);
        firstSideTable = ScoreTable.get(SIDE.BLACK,chessBoardxNumber,chessBoardyNumber);
        secondSideTable = ScoreTable.get(SIDE.WHITE,chessBoardxNumber,chessBoardyNumber);
        initDeskResult();
    }


    /**
     * 加入
     * @param player
     */
    public void join(Player player){
        if(twoSide[0] != null && twoSide[1] !=null){

        }else{
            if(twoSide[0] == null) {
                twoSide[0] = new Side();
                twoSide[0].side = SIDE.WHITE;
                twoSide[0].player = player;


                if(mType == TYPE.AI){
                    twoSide[1] = new Side();
                    Player aiplayer = new Player();
                    aiplayer.nickname="AI";
                    aiplayer.score = 1000;
                    aiplayer.userId = 0;
                    twoSide[1].player = aiplayer;
                    twoSide[1].side=SIDE.BLACK;

                }

            }

            if(twoSide[1]==null){
                twoSide[1] = new Side();
                twoSide[1].player = player;
                twoSide[1].side=SIDE.BLACK;
            }
        }
    }

    /**
     * 通知其他模块，棋盘的行为
     * @param action 动作
     * @param side 当前是哪一边的操作
     */
    public  void notifyAction(ACTION action,SIDE side){
        if(listeners!=null && listeners.size()>0){
            for (OnActionListener lister:
                 listeners) {
                lister.onAction(action,side);
            }
        }
    }

    /**
     * 重新开始
     * @param whoFirst
     */
    public void restart(SIDE whoFirst){
        initDeskResult();
        mCurrentSide.side=whoFirst;
        mCurrentSide.timeCount=timeCountEachStep;
        MoveTaskQuenue.historyMoves.clear();
        notifyAction(ACTION.RESTART, SIDE.NONE);
    }

    /**
     * 注册观察者
     * @param listener
     */
    public void registerObserver(OnActionListener listener){
        listeners.add(listener);
    }

    /**
     * 讲棋盘上所有点修改为没有使用
     */
    private void initDeskResult() {
        mDeskResult = new PointU[chessBoardxNumber][chessBoardyNumber];
        for (int i = 0; i < chessBoardxNumber; i++) {
            for (int j = 0; j < chessBoardyNumber; j++) {
                mDeskResult[i][j] = new PointU();
            }
        }
    }

    @Override
    public void onMoveFinish(int x, int y) {
        mDeskResult[x][y].belong = mCurrentSide.side;
        mDeskResult[x][y].x = x;
        mDeskResult[x][y].y = y;
        addHistory(x, y);

        LogUtils.d("onMoveFinish x=" + x + ",y=" + y + ",side=" + mCurrentSide.side);

        if(!checkSuccess()) {
            changeToNextSide();
        }else{
            onSuccess();
        }

        /**
         * AI模式，轮到AI
         */



        if(mType==TYPE.AI){
            if(mCurrentSide == twoSide[1]){
                notifyAction(ACTION.AI, mCurrentSide.side);
                //PointU next = mAiMachine.getNextStep(mDeskResult, 5);
                //onMoveFinish(next.x, next.y);

            //通知其他模块，AI正在操作
             }else{
                notifyAction(ACTION.NORMAL, mCurrentSide.side);
            }
        }

        //notifyAction(ACTION.NORMAL,mCurrentSide.side);

    }

    /**
     * 有人成功了
     */
    private void onSuccess() {

        Intent it = new Intent(RC.ACTION_SUCCESS);
        it.putExtra(RC.KEY_SIDE,mCurrentSide.side);
        ctx.sendBroadcast(it);
        LogUtils.d("sendSuccess");

    }

    private boolean checkSuccess() {
        VerifySuccess success = new VerifySuccess();
        successResult= success.verify(mDeskResult, successNumber);
        return (successResult.getRs().size() >= successNumber);
    }

    @Override
    public ChessBoard getBoard() {
        return this;
    }

    /**
     * 设置先手
     * @param s ，只能是0或者1
     */
    public void setFirstSide(int s){
        if(s==0) {
            mCurrentSide = twoSide[0];
        }else{
            mCurrentSide = twoSide[1];
        }

    }



    public void start(){

    }
    /**
     * 切换为另一边
     */
    private void changeToNextSide() {
        if (mCurrentSide.side.equals(twoSide[0].side)) {
            mCurrentSide = twoSide[1];
        } else {
            mCurrentSide = twoSide[0];
        }
        mCurrentSide.timeCount = timeCountEachStep;


        LogUtils.e("changeToNextSide",mCurrentSide.toString());

    }

    /**
     * 走完一步，加入历史记录
     * @param x
     * @param y
     */
    private void addHistory(int x, int y) {
        MoveTaskQuenue.Move move = new MoveTaskQuenue.Move();
        move.action = ACTION.NORMAL;
        move.point = new PointU(x,y);
        move.point.belong = mCurrentSide.side;
        move.who = mCurrentSide;
        MoveTaskQuenue.add(move);
    }

    public enum ACTION{
        //正常  悔棋
        NORMAL,RETRACT,RESTART,AI
    }

    public enum SIDE{
        WHITE,BLACK,NONE,DEBUG
    }

    public enum TYPE{
        AI,TWO
    }


    public enum DIRECT{
        TOP,TOP_RIGHT,
        RIGHT,RIGHT_BUTTON,
        BUTTOM,BUTTON_LEFT,
        LEFT,LEFT_TOP;
    }

}
